package com.aier.entrance.common;

import java.io.IOException;
import java.net.InetSocketAddress;

import javax.annotation.Resource;

import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
import org.springframework.beans.factory.InitializingBean;

import com.aier.common.common.Constant;
import com.aier.common.common.SystemConfigStatic;
import com.aier.entrance.icsocket.WatchingShortHandler;
import com.aier.entrance.service.IEntranceCardService;
import com.aier.entrance.service.IEntranceInitCommonService;

public class EntranceDeviceSysStart implements InitializingBean {

    @Resource(name = "entranceInitCommonService")
    private IEntranceInitCommonService entranceInitCommonService;
    @Resource(name = "entranceCardService")
    private IEntranceCardService entranceCardService;
    
    @Override
    public void afterPropertiesSet() throws Exception {
        entranceInitCommonService.initEntrance();
        // 创建UDP数据包NIO
        NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
        // NIO设置底层IOHandler
        acceptor.setHandler(new WatchingShortHandler(entranceCardService));

        // 设置是否重用地址？ 也就是每个发过来的udp信息都是一个地址？
        DatagramSessionConfig dcfg = acceptor.getSessionConfig();
        dcfg.setReuseAddress(true);

        // 绑定端口地址
        try {
            acceptor.bind(new InetSocketAddress(SystemConfigStatic.entrance_ip, Constant.num_8000));
        } catch (IOException e) {
            System.out.println("绑定接收服务器失败....");
            e.printStackTrace();
        }
        
    }

    public void setEntranceInitCommonService(
            IEntranceInitCommonService entranceInitCommonService) {
        this.entranceInitCommonService = entranceInitCommonService;
    }
    public void setEntranceCardService(IEntranceCardService entranceCardService) {
        this.entranceCardService = entranceCardService;
    }
    
}
